/*************************************************************************
> File Name: recv_multicast.c
> Author: hzy
> Created Time: 2023-09-20 11:28:01
> Description:
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        return -1;
    }

    // 设置套接字属性为多播地址（将多播地址加入到套接字中）
    struct ip_mreq addr;
    addr.imr_multiaddr.s_addr = inet_addr("224.0.0.1");
    addr.imr_interface.s_addr = htonl(INADDR_ANY); // 本机IP地址
    int ret = setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &addr, sizeof(addr));
    if (ret < 0)
    {
        perror("sockopt");
        return -1;
    }

    // 绑定应用程序端口
    struct sockaddr_in bind_addr;
    bind_addr.sin_family = AF_INET;
    // 给当前程序绑定一个自己制定的固定端口
    bind_addr.sin_port = htons(10086);
    // 给当前程序绑定一个ip地址
    bind_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    // 绑定套接字
    int bind_ret = bind(sockfd,
                        (struct sockaddr *)&bind_addr,
                        sizeof(bind_addr));
    if (bind_ret != 0)
    {
        perror("bind");
        exit(-1);
    }

    while (1)
    {
        char recv_buf[512] = {};
        struct sockaddr_in recv_addr;
        socklen_t addr_len = sizeof(recv_addr);
        // 接受消息
        int recv_ret = recvfrom(sockfd,
                                recv_buf,
                                sizeof(recv_buf),
                                0,
                                (struct sockaddr *)&recv_addr,
                                &addr_len);
        if (recv_ret < 0)
        {
            perror("recvfrom");
            break;
        }

        // 显示接受的内容
        char ip_buf[16] = {};
        inet_ntop(AF_INET,
                  &recv_addr.sin_addr.s_addr,
                  ip_buf,
                  INET_ADDRSTRLEN);
        printf("%s - %s\n", ip_buf, recv_buf);
    }

    close(sockfd);

    return 0;
}